package com.atshiyou.servlet;

import com.atshiyou.webDatabase.ConnectMysql;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print("<script>alert('请通过表单登录');location.href='./LoginForm.html'</script>");
    }



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String passwd = req.getParameter("upasswd");
        if(username == null || passwd == null){
            PrintWriter writer = resp.getWriter();
            writer.print("<script>alert('您的用户名或者密码为空，请重新填写');location.href='./index.html'</script>");
        }
        boolean b = false;
        try {
            b = ConnectMysql.checkUser(username, passwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //用户登录信息不正确返回index页面
        if (!b){
            PrintWriter printWriter = resp.getWriter();
            printWriter.write("<script>alert('您的账号或者密码错误，请重新登录!');location.href='./index.jsp'</script>");
            return;
        }
        //查询用户的积分
        int point1 = 0;
        try {
            point1 = ConnectMysql.findPoint(username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        //用户的登录信息正确，我们将用户的信息存入session中
        req.getSession().setAttribute("username",username);
        req.getSession().setAttribute("password",passwd);
        req.getSession().setAttribute("userPoint",point1);
        //跳转到登录成功的页面
        resp.sendRedirect("./success.jsp");

    }
}
